import { generateRequestKey } from './helper'

export let cache = new Map()

export class AxiosCache {
  clear () {
    const now = Date.now()
    for (const [k, v] of cache.entries()) {
      if (v.expires > now) continue
      cache.delete(k)
    }
  }

  get (config) {
    const key = generateRequestKey(config)
    const v = cache.get(key)
    if (!v) return null
    if (Date.now() > v.expires) {
      cache.delete(key)
      return null
    }
    return v.value
  }

  set (config, value, { timeout = 1 * 1000 }) {
    const key = generateRequestKey(config)
    cache.set(key, {
      value,
      expires: timeout + Date.now()
    })
    this.clear()
  }

  delete (config) {
    const key = generateRequestKey(config)

    cache.delete(key)
  }

  has (config) {
    const key = generateRequestKey(config)

    return this.get(key) !== null
  }
}
